package com.iqiu.cms.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.Name;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.rbac.UserLoginInfo;
import com.ibeetl.admin.core.service.CoreDictService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.util.HttpRequestLocal;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.iqiu.cms.baiduai.AiService;
import com.iqiu.cms.entity.CoreCompany;
import com.iqiu.cms.entity.CoreTestdata;
import com.iqiu.cms.entity.CoreUserMessage;
import com.iqiu.cms.service.*;
import com.iqiu.cms.util.EncryptUtil;
import com.iqiu.cms.util.Imagebase64;
import com.iqiu.cms.web.query.CoreAdQuery;
import com.iqiu.cms.web.query.CoreNoticeQuery;
import com.iqiu.cms.web.query.CoreTestdataQuery;
import com.iqiu.cms.web.query.CoreUserMessageQuery;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api")
public class ApiController {

    @Autowired
    CorePlatformService platformService;

    @Autowired
    CoreUserService userService;

    @Autowired
    HttpRequestLocal httpRequestLocal;

    @Autowired
    CoreDictService coreDictService;
    @Autowired
    Environment env;
    @Autowired
    CorePersonnelService corePersonnelService;
    @Autowired CoreNoticeService coreNoticeService;
    @Autowired CoreCompanyService coreCompanyService;
    @Autowired CoreTestdataService coreTestdataService;
    @Autowired CoreAdService coreAdService;
    @Autowired
    FileService fileService;
    @Autowired
    private CoreUserMessageService coreUserMessageService;


    @PostMapping("/app_update.do")
    @ResponseBody
    public JsonResult app_update(String version ,String name) {
        String android_version = env.getProperty("app.android_version", String.class, "1.0.0");
        if(!android_version.equals(version)){
            String wgtUrl = env.getProperty("app.wgtUrl", String.class, "");
            return JsonResult.success(wgtUrl);
        }
        return JsonResult.failMessage("已经是最新的");

    }

    @PostMapping("/login.do")
    @ResponseBody
    public JsonResult login(String code, String password, String imei, String clientid) {
        UserLoginInfo info = null;
        Object msg = userService.login_api(code, password);
        if (msg instanceof String) {
            return JsonResult.failMessage(msg.toString());
        } else info = (UserLoginInfo) msg;
        CoreUser user = info.getUser();
        if(user.getYouxiaoqi()!=null && user.getYouxiaoqi().getTime()<new Date().getTime()){
            return JsonResult.failMessage("您的资质已过期");
        }
        CoreCompany com=coreCompanyService.queryById(user.getComId());
        if(com.getYouxiaoqi()!=null && com.getYouxiaoqi().getTime()<new Date().getTime()){
            return JsonResult.failMessage("您所属公司的资质已过期");
        }
        // 记录登录信息到sessionuploadAttachment
        this.platformService.setLoginUser(info.getUser(), info.getCurrentOrg(), info.getOrgs());
        return JsonResult.success(user);
    }


    //修改密码
    @PostMapping("/updatePwd.do")
    @ResponseBody
    public JsonResult updatePwd(String pwd, String password, String id) {
        int count = userService.countInt(id, pwd);
        if (count == 0) {
            return JsonResult.failMessage("密码错误！");
        } else {
            userService.updatePwd(id, password);
        }
        return JsonResult.success("修改成功！");
    }

    //获取数据字典信息
    @RequestMapping("/getSelectData.do")
    @ResponseBody
    public JsonResult getSelectData(String t) {
        List<Name> educationList = coreDictService.educationList(t);
        return JsonResult.success(educationList);
    }
    //获取审批人信息
    @RequestMapping("/getInfo.do")
    @ResponseBody
    public JsonResult getInfo(String id) {
        CoreUser user = corePersonnelService.queryById(Long.parseLong(id));
        return JsonResult.success(user);
    }
    @RequestMapping("/getNotice.do")
    @ResponseBody
    public JsonResult<PageQuery> list(CoreNoticeQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        coreNoticeService.queryByCondition(page);
        return JsonResult.success(page);
    }
    @PostMapping("/testList.json")
    @ResponseBody
    public JsonResult<PageQuery> testList(CoreTestdataQuery condtion)
    {
        CoreUser user=corePersonnelService.queryById(condtion.getUserId());

        switch (condtion.getType()){
            case "bohui":
                condtion.setStatus("5,6");
                break;
            case "tongguo":
                condtion.setStatus("1");
                break;
            case "finish":
                condtion.setStatus("4");
                break;
            case "doing":
                condtion.setStatus("1");
                break;
            case "my":
                condtion.setCreateUser(condtion.getUserId() );
                break;
        }
        condtion.setComId(user.getComId());
        PageQuery page = condtion.getPageQuery();
        coreTestdataService.queryByCondition1(page);
        return JsonResult.success(page);
    }
    @PostMapping("/selectCount.do")
    @ResponseBody
    public JsonResult selectCount(Long userId)
    {
        CoreUser user=corePersonnelService.queryById(userId);
        Map m=new HashMap();
        m.put("comId",user.getComId());
        return new JsonResult().success(coreTestdataService.selectCount(m));
    }
    @PostMapping("/addTest.do")
    @ResponseBody
    public JsonResult addTest(@Validated(ValidateConfig.ADD.class) CoreTestdata coreTestdata)
    {
        coreTestdata.setDelFlag(0);
        coreTestdata.setCreateTime(new Date());
        CoreUser user=corePersonnelService.queryById(coreTestdata.getCreateUser());
        coreTestdata.setComId(user.getComId());
        coreTestdataService.save(coreTestdata);
        return new JsonResult().success();
    }

    @PostMapping("/adList.json")
    @ResponseBody
    public JsonResult<PageQuery> adList(CoreAdQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        coreAdService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping("/testDetail.json")
    @ResponseBody
    public JsonResult<CoreTestdata> testDetail(Integer id) {
        CoreTestdata coreTestdata = coreTestdataService.queryById( id);
        return  JsonResult.success(coreTestdata);
    }
    @PostMapping("/saveTest.do")
    @ResponseBody
    public JsonResult saveTest(CoreTestdata coreTestdata) {
        if(coreTestdata.getState()==2)
            coreTestdata.setTestDate(new Date());
        else if(coreTestdata.getState()==3)
            coreTestdata.setReportDate(new Date());
        try {
            String path=this.getClass().getResource("/").getPath();
            File file = new File(path+"/templates/cms/test/test"+coreTestdata.getId()+".html");
            if (file.createNewFile()) {
                file.setExecutable(true);//设置可执行权限
                file.setReadable(true);//设置可读权限
                file.setWritable(true);//设置可写权限
            }
            PrintStream printStream= new PrintStream(new FileOutputStream(path+"/templates/cms/test/test"+coreTestdata.getId()+".html"));//路径默认在项目根目录下
            printStream.println(coreTestdata.getHtmldata());
            coreTestdata.setHtmldata("1");
            coreTestdataService.updateTemplate( coreTestdata);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return  JsonResult.success();
    }
    @GetMapping("/test.do")
    @ResponseBody
    public ModelAndView test(Integer id) {
        CoreTestdata coreTestdata = coreTestdataService.queryById( id);
        ModelAndView view =null;
        if(StringUtils.isNotEmpty(coreTestdata.getHtmldata())){
            view=new ModelAndView("/cms/test/test"+id+".html") ;
        }else
            view=new ModelAndView("/cms/test/test.html") ;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(coreTestdata.getTestDate()==null)
            coreTestdata.setTestDate(new Date());
        view.addObject("test_date", sdf.format(coreTestdata.getTestDate()));
        view.addObject("coreTestdata",coreTestdata);
        return view;
    }
    @GetMapping("/testCode.do")
    @ResponseBody
    public ModelAndView testCode(String code) {
        String id= EncryptUtil.getInstance().AESdecode(code,"iqiu@321");
        CoreTestdata coreTestdata = coreTestdataService.queryById(id);
        ModelAndView view =null;
        if(StringUtils.isNotEmpty(coreTestdata.getHtmldata())){
            view=new ModelAndView("/cms/test/test"+coreTestdata.getId()+".html") ;
        }else
            view=new ModelAndView("/cms/test/test.html") ;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(coreTestdata.getTestDate()==null)
            coreTestdata.setTestDate(new Date());
        view.addObject("test_date", sdf.format(coreTestdata.getTestDate()));
        view.addObject("coreTestdata",coreTestdata);
        return view;
    }
    @PostMapping("/testFile.json")
    @ResponseBody
    public JsonResult testFile(Integer id) {
        return JsonResult.success(fileService.queryByBatchId(id.toString()));
    }
    @PostMapping("/face.do")
    @ResponseBody
    public JsonResult face(Long id) {
        FileItem item = fileService.getFileItemById(id);
        JSONObject obj=AiService.verifyUser(Imagebase64.getImageStrByte(item.getSrc()));
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            Map mp=objectMapper.readValue(obj.toString(2),Map.class);
            if(mp.get("error_msg").toString().equals("SUCCESS")){
                return JsonResult.success(mp.get("result"));
            }else{
                return JsonResult.failMessage(mp.get("error_msg").toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return JsonResult.failMessage("人脸识别识别");
    }

    /**
     * 修改GPS和检测人id
     * @return
     */
    @PostMapping("/updateGPS.json")
    @ResponseBody
    public JsonResult<CoreTestdata> updateGPS(CoreTestdata ct) {
        boolean su = coreTestdataService.updateTemplate( ct);
        return  JsonResult.success();
    }

    @RequestMapping("/getMessage.do")
    @ResponseBody
    public JsonResult getMessage(CoreUserMessageQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        coreUserMessageService.queryByCondition(page);
        return JsonResult.success(page);
    }


    //获取消息内容
    @RequestMapping("/messageDetail.do")
    @ResponseBody
    public JsonResult messageDetail( Integer id) {
        CoreUserMessage entity=new CoreUserMessage();
        entity.setId(id);entity.setIsRead(1);
        coreUserMessageService.updateTemplate(entity);//状态修改为已读
        CoreUserMessage list = coreUserMessageService.queryById(id);
        return JsonResult.success(list);
    }
}
